package me.zhengjie.schedule;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhengjie.dao.OutboundOrder;
import me.zhengjie.dao.OutboundOrderHistory;
import me.zhengjie.mapper.OutboundOrderHistoryMapper;
import me.zhengjie.mapper.OutboundOrderMapper;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class OutBoundSchedule {

    @Autowired
    private OutboundOrderMapper outboundOrderMapper;

    @Autowired
    private OutboundOrderHistoryMapper outboundOrderHistoryMapper;

    @Autowired
    private RedisUtils redisUtils;



    @Scheduled(cron = "0 0 0 * * ?")
    public void  outBoundRecordSchedule(){
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay(); // 当天的00:00:00
        LocalDateTime endOfDay = startOfDay.plusDays(1).minusSeconds(1); // 当天的23:59:59
        List<OutboundOrder> outboundOrders = outboundOrderMapper.selectList(new LambdaQueryWrapper<OutboundOrder>().between(OutboundOrder::getFinishTime, startOfDay, endOfDay)
                .eq(OutboundOrder::getStatus, 11));
        outboundOrders.forEach(e-> {
            OutboundOrderHistory history = new OutboundOrderHistory();
            history.setOutboundOrderNo(e.getOutboundOrderNo());
            history.setStatus(e.getStatus());
            history.setOutboundTime(e.getOutboundTime());
            history.setFinishTime(e.getFinishTime());
            history.setCreateTime(e.getCreateTime());
            outboundOrderHistoryMapper.insert(history);
        });


    }
    @Scheduled(cron = "0 0 0 * * ?")
    public void  delRedisTaskForThere(){
        String currentUsername ="System";
        try {
            currentUsername = SecurityUtils.getCurrentUsername();
        } catch (Exception e) {
        }
        // 检查键是否存在，如果不存在则初始化为 0
        if (!redisUtils.hasKey(currentUsername)) {
            redisUtils.set(currentUsername, 0L);
        }
    }
}
